package cn.xuqiudong.blog.base;

import cn.xuqiudong.blog.module.blog.model.RightAsideModel;
import cn.xuqiudong.blog.module.blog.service.BlogHomeService;
import cn.xuqiudong.common.base.web.intercept.SaveRequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述:   博客controller基类
 * @author Vic.xu
 * @since  2020/7/10 0010 13:30
 */
public abstract class BaseBlogController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected static final String PAGER = "pager";

    protected static final String LOOKUP = "lookup";

    @Autowired
    private BlogHomeService blogHomeService;

    /**
     * 保存在session中的右侧的数据
     */
    protected static final String RIGHT_MODEL_SESSION = "RIGHT_MODEL_SESSION";

    /**
     * 保存在session中的用户信息(第三方登录用户)
     */
    protected static final String PRINCIPAL_SESSION = "principal";

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    protected <T> T getSessionAttribute(String key) {
        return (T) WebUtils.getSessionAttribute(request, key);
    }

    protected void setSessionAttribute(String key, Object object) {
        WebUtils.setSessionAttribute(request, key, object);
    }

    /**
     * 返回通用的右侧数据
     */
    @ModelAttribute(name = "right")
    public RightAsideModel right() {
        RightAsideModel rightAsideModel = getSessionAttribute(RIGHT_MODEL_SESSION);
        if (rightAsideModel == null) {
            rightAsideModel = blogHomeService.queryRight();
            setSessionAttribute(RIGHT_MODEL_SESSION, rightAsideModel);
        }
        return rightAsideModel;
    }

    /**
     * 获取最后一次请求的url
     * @return url or /
     */
    protected String lastUrl() {
        String url = getSessionAttribute(SaveRequestInterceptor.LAST_URL);
        return StringUtils.isEmpty(url) ? "/" : url;
    }

}
